<template>
<div class="brand-profile-container">
  <el-card class="brand-card">
    <!-- 头部操作栏 -->
    <div class="card-header">
      <h2>{{ brandData.brandName }} 品牌管理</h2>
      <el-space>
        <el-button
          type="primary"
          :icon="Edit"
          @click="toggleEditMode"
          v-if="!isEditMode"
        >
          编辑资料
        </el-button>
        <template v-else>
          <el-button @click="cancelEdit">取消</el-button>
          <el-button
            type="success"
            :icon="Check"
            @click="submitForm"
            :loading="submitting"
          >
            保存更改
          </el-button>
        </template>
      </el-space>
    </div>

    <!-- 主体表单 -->
    <el-form ref="formRef" :model="formData" label-width="120px">
      <el-row :gutter="40">
        <!-- 左侧信息 -->
        <el-col :span="12">
          <el-form-item label="品牌ID" prop="brandId">
            <el-input v-model="formData.brandId" disabled />
          </el-form-item>

          <el-form-item label="品牌名称" prop="brandName" required>
            <el-input
              v-model="formData.brandName"
              :disabled="!isEditMode"
              placeholder="请输入品牌名称"
            />
          </el-form-item>

          <el-form-item label="品牌描述" prop="brandDescription">
            <el-input
              v-model="formData.brandDescription"
              :disabled="!isEditMode"
              type="textarea"
              :rows="4"
              resize="none"
              placeholder="请输入品牌描述"
            />
          </el-form-item>
        </el-col>

        <!-- 右侧媒体 -->
        <el-col :span="12">
          <el-form-item label="品牌Logo">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8081/upload"
              :show-file-list="false"
              :disabled="!isEditMode"
              :before-upload="beforeUploadLogo"
              :on-success="handleLogoSuccess"
            >
              <img
                v-if="formData.brandLogoUrl"
                :src="formData.brandLogoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="背景图片">
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:8081/upload"
              :show-file-list="false"
              :disabled="!isEditMode"
              :before-upload="beforeUploadBackground"
              :on-success="handleBackgroundSuccess"
            >
              <img
                v-if="formData.backgroundImageUrl"
                :src="formData.backgroundImageUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 统计信息 -->
    <div class="stats-panel">
      <el-statistic title="平均评分" :value="brandData.averageRating" :precision="1" />
      <el-statistic title="好评数量" :value="brandData.positiveReviewsCount" />
      <el-statistic title="总销售额" :value="brandData.salesVolume" :precision="2">
        <template #suffix>元</template>
      </el-statistic>
    </div>
  </el-card>
</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { Check, Edit, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useLoginStore } from '@/stores/login';
import { updateBrand } from '@/common/net/api';

const brandStore = useLoginStore();
const formRef = ref();
const isEditMode = ref(false);
const submitting = ref(false);

// 从Pinia获取完整品牌数据
const brandData = computed(() => brandStore.brand);

// 表单数据（仅可编辑字段）
const formData = reactive({
  brandId: 0,
  brandName: '',
  brandLogoUrl: '',
  brandDescription: '',
  backgroundImageUrl: ''
});

// 初始化表单数据
const initForm = () => {
  Object.assign(formData, {
    brandId: brandData.value.brandId,
    brandName: brandData.value.brandName,
    brandLogoUrl: brandData.value.brandLogoUrl,
    brandDescription: brandData.value.brandDescription,
    backgroundImageUrl: brandData.value.backgroundImageUrl
  });
};

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
  initForm();
};

// 取消编辑
const cancelEdit = () => {
  isEditMode.value = false;
  initForm();
};

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true;
    await updateBrand(formData);
    ElMessage.success('品牌信息更新成功');
    isEditMode.value = false;
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message);
  } finally {
    submitting.value = false;
  }
};

// 初始化数据
initForm();

// 获取 Token
const token = computed(() => localStorage.getItem('token'));

// 上传前校验
const beforeUploadLogo = (file: File) => {
  return beforeUpload(file, 'Logo');
};

const beforeUploadBackground = (file: File) => {
  return beforeUpload(file, '背景图');
};

const beforeUpload = (file: File, type: string) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isValidType) {
    ElMessage.error(`${type} 只能上传 JPG/PNG 格式!`);
    return false;
  }
  if (!isLt5M) {
    ElMessage.error(`${type} 图片大小不能超过 5MB!`);
    return false;
  }
  return true;
};

// 上传成功处理
const handleLogoSuccess = (res: any) => {
  if (res.state) {
    formData.brandLogoUrl = res.data;
    ElMessage.success('Logo 上传成功');
  } else {
    ElMessage.error('Logo 上传失败: ' + res.message);
  }
};

const handleBackgroundSuccess = (res: any) => {
  if (res.state) {
    formData.backgroundImageUrl = res.data;
    ElMessage.success('背景图上传成功');
  } else {
    ElMessage.error('背景图上传失败: ' + res.message);
  }
};
</script>

<style scoped lang="scss">
.brand-profile-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;

  .brand-card {
    padding: 2rem;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2rem;

    h2 {
      margin: 0;
      font-size: 1.5rem;
      color: #333;
    }
  }

  .stats-panel {
    margin-top: 2rem;
    padding: 1.5rem;
    background: #f8f9fa;
    border-radius: 8px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 2rem;

    :deep(.el-statistic) {
      text-align: center;

      .el-statistic__label {
        font-size: 0.9rem;
        color: #666;
      }

      .el-statistic__content {
        font-size: 1.5rem;
        font-weight: 600;
        color: #2c3e50;
      }
    }
  }
}

.avatar-uploader {
  .avatar {
    height: 200px;
    object-fit: cover;
    border-radius: 8px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    line-height: 100px;
    text-align: center;
  }
}
</style>
